<template>
	<view style="background-color: #fff;">
		<u-navbar :isBack="true" title="师傅入驻" title-color="#111111" back-icon-color="#111111"
		:background="{background: 'white'}" :borderBottom="false"></u-navbar>
		<view class="" style="padding: 24rpx;">
			<!-- <u-form ref="form" class="detail-form" label-width="200rpx" :label-style="{ color: '#333333' }"
				:model="formModal"> -->
				<public-form-group>
					<!-- <u-gap height="180" bg-color="#FFF"></u-gap> -->
					<view style="color: #111111;font-size: 32rpx;font-weight: bold;">完善个人信息</view>
					<u-form-item label="姓名" prop="owner" label-width="140rpx">
						<input class="u-flex-1" v-model="formModal.name" type="text" placeholder="请填写您的姓名" :disabled="isEnable"/>
					</u-form-item>
					<u-form-item label="联系电话" prop="mobile" label-width="140rpx">
						<input class="u-flex-1" v-model="formModal.mobile" type="number" placeholder="请填写您的联系电话"  :disabled="isEnable"/>
					</u-form-item>
					<u-form-item label="常驻地" prop="grade" label-width="140rpx">
						<view v-if="!isEnable" class="u-flex u-flex-1 link-active" @click="toMapSelection">
							<label class="u-flex-1" >{{ location_str }}</label>
							<u-icon name="map" color="#18cba2" label-size="40"></u-icon>
						</view>
						<view v-else class="u-flex u-flex-1 link-active">
							<label class="u-flex-1">{{ location_str }}</label>
						</view>
					</u-form-item>
					<view style="color: #333333;font-size: 32rpx;padding: 24rpx 0rpx;">
						请上传身份证正反面
					</view>
					<view style="width: 100%">
						<view v-if="!isEnable"  @click="uploadIdCard">
							<image :src="idcard_front_full" mode="scaleToFill" style="width: 100%;"
								v-if="idcard_front_full"></image>
							<image src="/static/my/sfz.png" mode="widthFix" style="width: 100%;" v-else></image>
						</view>
						<view v-else >
							<image :src="idcard_front_full" mode="scaleToFill" style="width: 100%;"
								v-if="idcard_front_full"></image>
						</view>
					</view>
					<view style="width: 100%;margin-top: 24rpx;">
						<view v-if="!isEnable" @click="uploadIdCard(false)">
							<image :src="idcard_back_full" mode="scaleToFill" style="width: 100%;" v-if="idcard_back_full">
							</image>
							<image src="/static/my/sfz.png" mode="widthFix" style="width: 100%;" v-else></image>
						</view>
						<view v-else >
							<image :src="idcard_back_full" mode="scaleToFill" style="width: 100%;"
								v-if="idcard_back_full"></image>
						</view>
					</view>
				</public-form-group>
				<u-gap height="24" bg-color="#F5F5F5"></u-gap>
				<view class="" style="margin: 32rpx;background: #fff;margin-left: 0;">
					<view style="color: #111111;font-size: 32rpx;font-weight: bold;">选择合作商家</view>
				</view>
				<!-- <view class="order-map-control">
					<map id="Map" ref="Map" style="width: 100vw; height: 100%;position: relative;" :longitude="d_location_longitude" :latitude="d_location_latitude" scale='15' :markers="marker" @markertap="chooseBranch" enable-building="true" show-location>
						<cover-view class="my-location">
								<cover-image class="img" src="https://course.jchen.art/static/images/icon-location.png" @click="goLocation()"></cover-image>
						</cover-view>
					</map>
				</view> -->
				<view style="display: flex;align-items: center;padding: 10rpx 0;">
					<view class="title" style="width: 160rpx;">合作商家</view>
					<view class="tn-flex tn-flex-row-between" style="width: 100%;padding: 10rpx;display: flex;justify-content: space-between;"
						@click="branchShow = true">
						<view style="color: #111111;" v-if="branchData.label">{{ branchData.label }}</view>
						<view style="color: #848282;" v-else>请选择合作商家</view>
						<!-- <image src="@/static/icon/ri.png" mode="widthFix" style="width: 16px;"></image> -->
					</view>
				</view>
				
				
				<u-gap height="24" bg-color="#F5F5F5"></u-gap>
				<view class="" style="margin: 32rpx;background: #fff;margin-left: 0;">
					<view style="color: #111111;font-size: 32rpx;font-weight: bold;">完善技能信息</view>
				</view>
				<public-form-group>
					<u-form-item label="服务工种" prop="work" label-width="140rpx">
						<view v-if="!isEnable" class="u-flex u-flex-1 link-active" @click="skillChoose()">
							<!-- <input class="u-flex-1" v-model="formModal.work" type="text" placeholder="请选择您拥有的技能" @click="skillChoose()"/> -->
							<view  class="u-flex-1"style="color: #848282;">请选择您拥有的技能</view>
							<u-icon name="arrow-right"></u-icon>
						</view>
						<view v-else class="u-flex u-flex-1 link-active">
							<input class="u-flex-1"  type="text" placeholder="服务工种" disabled="true"/>
						</view>
					</u-form-item>
					<view style="display: flex; flex-wrap: wrap;margin-top: 24rpx;">
						<view v-for="(item,index) in craftList" :key="index" v-if="item.selected">
							<view style="color: #FC7404;padding: 8rpx 24rpx;border-radius: 8rpx;
							font-size: 24rpx;background: #FEEEE0;margin-right: 24rpx; margin-bottom: 10rpx;">{{item.name}}</view>
						</view>
					</view>
					<!-- <u-form-item v-if="!isEnable" label="请上传相关技能证件" prop="" label-position="top">
						<view style="width: 100%"> -->
							<!-- <view class="upload-btn box-active"></view> -->
							<!-- <u-upload @on-choose-complete="onChooseComplete" @on-remove="onImgRemove"
								:show-upload-list="true" :auto-upload="false" :file-list="fileList" :show-progress="true"
								:deletable="true" max-count="10"></u-upload> -->
							<!-- <text class="tips-text">
						  注：请上传您资质证书，最多10张，要求清晰，大小1M内
						</text> -->
						<!-- </view>
					</u-form-item> -->
				</public-form-group>
			<!-- </u-form> -->
		</view>
		<view class="u-p-t-40 u-text-center">
			<view class="u-flex u-p-l-30" @click="agreementBtn">
				<u-checkbox-group @change="agreementBtn">
					<u-checkbox v-model="agreementFlag"></u-checkbox>
				</u-checkbox-group>
				我已阅读并同意<span style="color:#014c8c" :key="agreementFlag"
					@click.stop="agreementTextBtn">《用户协议和隐私政策》</span>
			</view>
		</view>
		<view style="background-color: #fbfbfb">
			<button class="u-reset-button confirm-btn" @tap="submit">提交申请</button>
			<view class="safe-area-inset-bottom"></view>
		</view>
		<view style="height: 60rpx;"></view>

		<!-- 选择业务类型 -->
		<u-popup v-model="skillShow" mode="bottom">
			<view style="padding: 32rpx;border: solid 1px #F5F5F5;display: flex; font-size: 32rpx;">
				<view style="color: #333;" @click="skillShow = false">取消</view>
				<view style="color: #FC7404; flex: 1; margin-left: 10rpx;" @click="selectAll">全选</view>
				<view style="color: #FC7404;font-weight: bold;" @click="skillYes">确定</view>
			</view>
			<view style="padding: 32rpx;">
				<public-form-group>
					<u-form-item :label="item.name" prop="work" label-width="140" v-for="(item,index) in craftList"
						:key="item.id">
						<view class="u-flex u-flex-1 link-active">
							<view class="u-flex-1"></view>
							<u-checkbox v-model="item.selected"></u-checkbox>
						</view>
					</u-form-item>
				</public-form-group>
			</view>
		</u-popup>
		
		<u-select v-model="branchShow" mode="mutil-column-auto" label-name="nickname" value-name="id" :list="branchList"
			@confirm="branchCofirm"></u-select>
		
		<!-- <uni-popup ref="frmAgreement" type="center" :animation="false">
			<view
				style="width: 90vw; background-color: #FFF; padding: 30rpx; border-radius: 10rpx; display: flex; flex-direction: column; height: 80vh;">
				<scroll-view style="height: 70vh;" :scroll-y="true">
					<rich-text :nodes="specAgreement"></rich-text>
				</scroll-view>
				<button
					style="background-color: #FC7404; color: #FFF; height: 60rpx; width: 80%; margin-top: 20rpx; font-size: 26rpx;"
					@click="closeAgreement">阅读完成</button>
			</view>
		</uni-popup> -->
	</view>
</template>

<script>
	import configUrl from '@/utils/config.js';
	import { request } from 'utils/request.js';
	export default {
		name: "FinanceRegister",
		data() {
			return {
				skillShow: false,
				branchShow:false,
				branchData:{},
				branchList:[],
				craftList: [],

				isShow: false,
				isEnable:false,

				value: '20',
				positioning: configUrl.appurlImg + '/app/ddingwei.png',
				mrsfzzimg: configUrl.appurlImg + '/app/sfzz.png',
				mrsfzfimg: configUrl.appurlImg + '/app/sfzf.png',

				idcard_front_full: "",
				idcard_back_full: "",
				agreementFlag: false, //注册协议选中状态

				formModal: {
					isEdit:false,
					name: "",
					mobile: "",
					idcard_front: "",
					idcard_back: "",
					craft_ids: "",
					certificate_images: "",
					location_longitude: "",
					location_latitude: "",
					branch_id:"",
					location_str:''
				},
				location_str: "请选择您的常驻地址",
				specAgreement: "许可协议",
				// rules: {},
				imagesList2: [],
				fileList: [],
				fileListUrls: [],
				header: {
					'token': ''
				},
				d_location_longitude:'',
				d_location_latitude:'',
				marker:[],
				mapCtx: null,
			};
		},
		onReady() {
			// this.mapCtx = uni.createMapContext('Map', this);
		},
		onLoad() {
			let self = this;

			// userApi.queryMasterApply().then(res => {
			// 	if (res == '-1') {
			// 		self.isShow = true;
			// 	}else if (res == '-2') {
			// 		uni.showToast({
			// 			title: '请先绑定手机号！',
			// 			duration: 2000,
			// 			icon: "none",
			// 		});
			// 		setTimeout(() => {
			// 			uni.navigateTo({
			// 				url: '/pages/users/MyInfo?action=mobile',
			// 			})
			// 		},2000);
			// 	} else {
			// 		self.isShow = true;
			// 		self.isEnable = true;
			// 		self.formModal.isEdit = true;
			// 		setTimeout(() => {
			// 			self.getApplyInfo();
			// 		}, 1000)
			// 	}
			// });
			// 获取工种
			this.getGoodsCategory();
			// 获取商家列表
			this.getMerchantGetLis();
			// let person_location = uni.getStorageSync("location_str");
			// let locationList = person_location.split(',');
			// self.d_location_longitude = '108.335462';//locationList[0];
			
			// self.d_location_latitude = '22.852586';//locationList[1];
			
			// self.showNearBranch(locationList[0],locationList[1]);
			
			// uni.getLocation({
			// 	type: 'gcj02',
			// 	success(res) {
			// 		console.log('获取经纬度: ', res)
			// 		self.d_location_longitude = res.longitude;//locationList[0];
			// 		self.d_location_latitude = res.latitude;//locationList[0];
			// 		setTimeout(() => {
			// 			// self.showNearBranch(res.longitude,res.latitude);
			// 			// self.getNearMechanic(res.longitude,res.latitude);
			// 		}, 2000)
			// 	}
			// });

		},
		methods: {
			getGoodsCategory(){
				request.postWithToken({
					url: '/merchant/getGoodsCategory',
					data: {page: 1}
				}).then(res=>{
					console.log(res);
					this.craftList = res.data;
				})
			},
			getMerchantGetLis(){
				request.getWithToken({
					url: '/merchant/getLis',
					data: {page: 'all'}
				}).then(res=>{
					console.log(res);
					this.branchList = res.data.dataList;
				})
			},
			goLocation(){
				setTimeout(() => {
					this.mapCtx.moveToLocation({
						longitude:this.d_location_longitude,
						latitude:this.d_location_latitude
					});
				}, 500)
			},
			getApplyInfo(){
				let _this = this;
				console.log(_this.craftList)
				userApi.getApplyInfo().then(res => {
					
					_this.formModal = res;
					_this.location_str = res.location_str
					
					_this.idcard_front_full= configUrl.appurlImg + res.idcard_front;
					_this.idcard_back_full= configUrl.appurlImg + res.idcard_back;
					
					for(let c = 0; c < _this.craftList.length; c++){
						if((','+res.craft_ids+',').includes(','+_this.craftList[c].id+',')){
							_this.craftList[c].selected = true;
						}
					}
					let image = res.certificate_images.split(',');
					for(let i = 0;i < image.length;i++){
						image[i] = configUrl.appurlImg +image[i];
					}
					// _this.fileListUrls = image;
					// _this.fileList = image;
					// console.log(image,'55555555')
					
				});
				console.log(_this.marker)
			},
			chooseBranch(e){
				console.log(e,'marker')
				this.formModal.branch_id = e.detail.markerId;
				let choose = [];
				for(let i = 0;i < this.branchList.length;i++){
					if(this.branchList[i].id == e.detail.markerId){
						choose.push({
							label:this.branchList[i].title,
							value:e.detail.markerId
						})
					}
				}
				this.branchCofirm(choose);
				console.log(this.branchData,'marker')
			},
			branchCofirm(e) {
				console.log('confirm', e);
				this.formModal.branch_id = e[0].value;
				this.branchData = e[0];
				this.branchShow = false;
			},
			showNearBranch(longitude,latitude){
				let _this = this;
				
				userApi.getNearBranch({longitude:longitude, latitude:latitude}).then(res => {
					_this.marker = []
					_this.marker = res;
					_this.branchList = res;
				});
				console.log(_this.marker)
				
				// _this.marker.push(_this.orderDestMarker);
				// _this.marker.push({
				// 	id: item.id,
				// 	longitude: item.longitude,
				// 	latitude: item.latitude,
				// 	thumbImg: configUrl.appurlImg + item.thumbImg,
				// 	distance: item.distance,
				// 	width: 20,
				// 	height: 20,
				// 	title:item.name,
				// 	iconPath: configUrl.appurlImg + item.thumbImg,
				// 	customCallout: {
				// 		display: 'ALWAYS'
				// 	}
				// });
			},
			skillChoose() {
				console.log('skillList---111', this.skillShow);
				this.skillShow = true;
			},
			skillYes() {
				console.log('skillList---', this.craftList);
				let cids = [];
				this.craftList.forEach(element => {
					if (element.selected) cids.push(element.id);
				});
				this.formModal.craft_ids = cids.join(",");
				this.skillShow = false;
			},
			selectAll() {
				console.log('skillList---', this.craftList);
				let cids = [];
				this.craftList.forEach(item => {
					item.selected = true;
					cids.push(item.id);
				});
				this.formModal.craft_ids = cids.join(",");
				this.skillShow = false;
			},
			closeAgreement() {
				this.$refs.frmAgreement.close();
			},
			//选中注册协议按钮
			agreementBtn() {
				this.agreementFlag = !this.agreementFlag;
			},
			//注册协议
			agreementTextBtn() {
				// this.agreementTextFlag = !this.agreementTextFlag;
				// this.show2 = true;
				this.$refs.frmAgreement.open();
			},
			// 选中任一radio时，由radio-group触发
			radioGroupChange(e) {
				console.log(e);
			},
			gradeConfirm(e) {
				console.log('confirm', e);
				this.formModal.grade = e[0].label;
				this.gradeShow = false;
			},
			practiceConfirm(e) {
				console.log('confirm', e);
				this.formModal.practice = e[0].label;
				this.practiceShow = false;
			},
			workConfirm(e) {
				console.log('confirm', e);
				this.formModal.work = e[0].label;
				this.workShow = false;
			},
			uploadIdCard(isFront = true) {
				let _this = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						_this.uploadFilePaths(res.tempFilePaths[0], isFront);
					}
				});
			},
			uploadFilePaths(url, isFront) {
				let _this = this;
				request.uploadFileImg({
					url: '/common/upload',
					data: url,
				}).then(res => {
					console.log('图片路径', res);
					// that.formData.logo = res;
					if (isFront) {
						_this.formModal.idcard_front = res;
						_this.idcard_front_full = res;
					} else {
						_this.formModal.idcard_back = res;
						_this.idcard_back_full = res;
					}
				});
				return;
				uni.uploadFile({
					url: configUrl.appurl + `/auth/uploadCertification`,
					filePath: url,
					name: 'file',
					header: {
						'token': uni.getStorageSync('token'),
					},
					success: (uploadFileRes) => {
						console.log('uploadFileRes：', uploadFileRes);
						let result = uploadFileRes.data;
						if (uploadFileRes.statusCode == 401) {
							uni.removeStorageSync('token')
							uni.navigateTo({
								url: '/pages/auth/Login',
							})
						}
						if (uploadFileRes.statusCode == 200) {
							result = JSON.parse(result);
							if (result.code == 1) {
								console.log('返回信息：', result);
								if (isFront) {
									_this.formModal.idcard_front = result.data.url;
									_this.idcard_front_full = result.data.fullurl;
								} else {
									_this.formModal.idcard_back = result.data.url;
									_this.idcard_back_full = result.data.fullurl;
								}
							} else {
								uni.showToast({
									title: result.msg,
									duration: 2000,
									icon: "none",
								});
							}
						}
					}
				});
			},
			submit() {
				this.formModal.certificate_images = this.fileListUrls.join(",");
				if (!this.agreementFlag) {
					uni.showToast({
						title: "请先阅读并勾选许可协议",
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				request.postWithToken({
					url: '/master/applyData',
					data: this.formModal
				}).then(res=>{
					console.log(res);
					if(res.code == 1){
						uni.showToast({
							title: '申请成功，等待审核...',
							duration: 2000,
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							});
						}, 800);
					}else{
						// this.$refs.uToast.show({ title: res.msg });
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						});
					}
				})
				// userApi.applyMaster(this.formModal).then(res => {
				// 	uni.showToast({
				// 		title: "提交成功",
				// 		duration: 2000,
				// 		icon: 'none'
				// 	});
				// 	uni.navigateTo({
				// 		url: '/pages/master/result?action=0',
				// 	});
				// });
			},
			onImgRemove(index, lists, name) {
				this.fileListUrls.splice(index, 1);
			},
			onChooseComplete(lists, name) {
				this.fileList = [];
				this.fileListUrls = [];
				let self = this;
				lists.forEach(img => {
					uni.uploadFile({
						url: configUrl.appurl + `/auth/uploadCertification`,
						filePath: img.url,
						name: 'file',
						header: {
							'token': uni.getStorageSync('token'),
						},
						success: (uploadFileRes) => {
							console.log('uploadFileRes：', uploadFileRes);
							let result = uploadFileRes.data;
							if (uploadFileRes.statusCode == 401) {
								uni.removeStorageSync('token')
								uni.navigateTo({
									url: '/pages/auth/Login',
								})
							}
							if (uploadFileRes.statusCode == 200) {
								result = JSON.parse(result);
								if (result.code == 1) {
									console.log('返回信息：', result.data);
									// self.fileList.push(result.data.fullurl);
									self.fileListUrls.push(result.data.url);
								} else {
									uni.showToast({
										title: result.msg,
										duration: 2000,
										icon: "none",
									});
								}
							}
						}
					});
				});
			},
			toMapSelection() {
				let self = this;
				uni.chooseLocation({
					success: (res)=> {
						console.log('选择位置：', res)
						self.formModal.latitude = res.latitude;
						self.formModal.longitude = res.longitude;
						self.formModal.location_str = res.address + res.name;
						self.location_str = res.address + res.name;
					}
				});
				return;
				uni.$off('pickMap');
				uni.$on('pickMap', function(point) {
					self.formModal.location_latitude = point.latitude;
					self.formModal.location_longitude = point.longitude;
					self.formModal.location_str = point.exactAddress;
					self.d_location_latitude = point.latitude;
					self.d_location_longitude = point.longitude;
					self.location_str = point.exactAddress;
					self.showNearBranch(point.longitude,point.latitude)
					uni.$off('pickMap');
				});
				uni.navigateTo({
					url: '/pages/users/MapSelection?title=选择常驻地址'
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	// @import "static/css/public-custom-form.scss";

	.upload-btn {
		position: relative;
		width: 140rpx;
		height: 140rpx;
		border: 0.5px solid #999;
		border-radius: 8rpx;

		&::before,
		&::after {
			position: absolute;
			left: 50%;
			top: 50%;
			display: block;
			width: 50%;
			border-top: 0.5px solid #999;
			content: '';
			transform: translate(-50%, -50%);
		}

		&::after {
			transform: translate(-50%, -50%) rotate(90deg);
		}
	}

	.tips-text {
		font-size: 24rpx;
		color: #b2b2b2;
	}
.order-map-control {
		width: 100%;
		height: 40vh;
		background-color: #FFF;
		padding: 0;
	}
	.confirm-btn {
		margin: 32rpx;
		// width: calc(100vw - 44rpx);
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		color: #fff;
		background-color: #FC7404;
		// border-radius: 999px;
		font-size: 32rpx;
		border-radius: 24rpx;

		&:active {
			background-color: lighten(#FC7404, 10%);
		}
	}
	.my-location {
		position: absolute;
			right: 30rpx;
			bottom: 30rpx;
		
			.img {
				width: 50rpx;
				height: 50rpx;
			}
		}

	page {
		background: #F5F5F5 !important;
	}
</style>
